package org.cornland.systemWarning.schedule;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.cornland.systemWarning.model.DataExceptionAlarm;
import org.cornland.systemWarning.model.DataExceptionAlarmConfig;
import org.cornland.systemWarning.model.RealdataTag;
import org.cornland.systemWarning.service.DataExceptionAlarmConfigService;
import org.cornland.systemWarning.service.DataExceptionAlarmService;
import org.cornland.systemWarning.service.RealdataTagService;
import org.cornland.systemWarning.utils.AppUrl;
import org.cornland.systemWarning.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.net.URI;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class ControllerSchedule {

    @Autowired
    AppUrl appUrl;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    RealdataTagService realdataTagService;

    @Autowired
    DataExceptionAlarmService dataExceptionAlarmService;

    @Autowired
    private DataExceptionAlarmConfigService dataExceptionAlarmConfigService;

    @Scheduled(cron = "0 0/10 * * * ?")
    public void controllerWarningSchedule(){
        try {
            log.info("控制器异常信息检查开始");
            controllerWarning();
            log.info("控制器异常信息检查结束");
        } catch (ParseException e){
            log.error("ParseException,请检查");
            log.error(e.getMessage(), e);
        } catch (RestClientException e){
            log.error("请求接口超时,请检查");
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error("控制器异常信息检查遇到问题");
            log.error(e.getMessage(), e);
        }
    }


    public void controllerWarning() throws ParseException {
        List<RealdataTag> wellWithControllerTag = realdataTagService.getExistControllerTag();
        for (int i = 0; i <wellWithControllerTag.size() ; i++) {
            RealdataTag realdataTag = wellWithControllerTag.get(i);
            String statusTag = realdataTag.getStatusTag();
            String jmjh = realdataTag.getJmjh();
            String wellId = realdataTag.getWellId();
            // 检查是否有状态点位
            // 有责调用查询接口
            if(!StringUtil.isNullOrEmpty(statusTag)){

                // 实时数据接口
                String url = appUrl.queryRealTimeDataUrl + "?tags=" + statusTag;
                URI uri = URI.create(url);
                String tagString = restTemplate.getForObject(uri, String.class);

                // 调用实时数据接口 返回jsonArray
                JSONArray jsonArray = JSONArray.parseArray(tagString);

                if(jsonArray.size()!=0){
                    Map<String,Object> statusMap = jsonArray.getObject(0, Map.class);
                    String value = (String) statusMap.get("value");
                    String outTime = (String) statusMap.get("time");

                    // value是否为空
                    if(!StringUtil.isNullOrEmpty(value)){
                        Map<String,Object> valueMap = JSON.parseObject(value, Map.class);
                        String inTime = (String) valueMap.get("time");

                        // time是否为空 里面的time为空则取外面的
                        // 只要有值应该都有外时间
                        if(!StringUtil.isNullOrEmpty(inTime)){
                            inTime = DateUtil.dateFormat(inTime);
//                            log.info(jmjh+" 控制器时间为:" + inTime);
                            if(!DateUtil.inFiveMin(inTime)){

                                String message = "控制器时间异常,控制器时间为" + inTime;

                                DataExceptionAlarm last = dataExceptionAlarmService.getLast(wellId, 1);

                                // 不存在上一条 直接存
                                if(last == null){
                                    saveControllerException(wellId, message);
                                }
                                else{
                                    Integer flag = last.getFlag();
                                    // 如果上一条信息未处理则不做任何动作
                                    // 如果上条已处理则添加
                                    if(flag == 1){
                                        saveControllerException(wellId, message);
                                    }

                                }

                            }
                        }else{
//                            log.info(jmjh+" 控制器时间取外时间为:" + DateUtil.dateFormat(outTime));
                            if(!DateUtil.inFiveMin(outTime)){
                                String message = "控制器时间异常,控制器时间为" + outTime;

                                DataExceptionAlarm last = dataExceptionAlarmService.getLast(wellId, 1);

                                // 不存在上一条 直接存
                                if(last == null){
                                    saveControllerException(wellId, message);
                                }
                                else{
                                    Integer flag = last.getFlag();
                                    // 如果上一条信息未处理则不做任何动作
                                    // 如果上条已处理则添加
                                    if(flag == 1){
                                        saveControllerException(wellId, message);
                                    }

                                }
                            }
                        }
                    }
                    else{
                        // value值为空
//                        log.warn(jmjh + "value查询为空");
                    }


                }
                else{
                      // 点位array为[]
//                    log.warn(jmjh + "点位查询为空");
                }


            }
            else{
                // 井没有状态点 可以做提示
//                log.info(jmjh+"未发现状态运维状态点位");
            }

        }


    }


    public void saveControllerException(String wellId, String message){
        //获取当前时间
        String nowTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        DataExceptionAlarmConfig dataExceptionAlarmConfig = dataExceptionAlarmConfigService.getOne(new QueryWrapper<DataExceptionAlarmConfig>().eq("type", 1));
        boolean b=false;
        if(StringUtils.isNotBlank(dataExceptionAlarmConfig.getBeganIgnore())){
            b = DateUtil.compareTime(dataExceptionAlarmConfig.getBeganIgnore(), dataExceptionAlarmConfig.getEndIgnore(), nowTime);
        }
        if(!b){
            //        log.info(jmjh+"控制器时间异常");
            DataExceptionAlarm dataExceptionAlarm = new DataExceptionAlarm();
            dataExceptionAlarm.setWellId(wellId);
            dataExceptionAlarm.setTime(DateUtil.getCurrentTimeFormat());
            dataExceptionAlarm.setFlag(0);
            dataExceptionAlarm.setType(1);
            dataExceptionAlarm.setDescription(message);
            dataExceptionAlarmService.save(dataExceptionAlarm);
        }

    }




}
